/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.cloud.business.usercenter.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.lvyh.lightframe.cloud.business.usercenter.service.SysMenuService;
import com.lvyh.lightframe.cloud.common.annotation.CurrentUser;
import com.lvyh.lightframe.cloud.common.constant.SystemConstants;
import com.lvyh.lightframe.cloud.common.model.PageResult;
import com.lvyh.lightframe.cloud.common.model.Result;
import com.lvyh.lightframe.cloud.common.model.SysMenu;
import com.lvyh.lightframe.cloud.common.model.SysRole;
import com.lvyh.lightframe.cloud.common.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/menus")
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;

    public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
        List<SysMenu> menus = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            if (ObjectUtil.equal(-1, sysMenu.getParentId())) {
                menus.add(sysMenu);
            }
            for (SysMenu menu : sysMenus) {
                if (menu.getParentId().equals(sysMenu.getId())) {
                    if (sysMenu.getSubMenus() == null) {
                        sysMenu.setSubMenus(new ArrayList<>());
                    }
                    sysMenu.getSubMenus().add(menu);
                }
            }
        }
        return menus;
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        try {
            sysMenuService.removeById(Integer.parseInt(Long.toString(id)));
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("memu-delete-error", ex);
            return Result.failed("操作失败");
        }
    }

    @GetMapping("/{roleId}/menus")
    public List<Map<String, Object>> findMenusByRoleId(@PathVariable Long roleId) throws Exception {
        List<Integer> roleIds = new ArrayList<>();
        roleIds.add(Integer.parseInt(Long.toString(roleId)));

        List<SysMenu> roleMenus = sysMenuService.findByRoles(roleIds);

        List<SysMenu> allMenus = sysMenuService.findAll();
        List<Map<String, Object>> authTrees = new ArrayList<>();

        Map<Integer, SysMenu> roleMenusMap = roleMenus.stream().collect(Collectors.toMap(SysMenu::getId, SysMenu -> SysMenu));

        for (SysMenu sysMenu : allMenus) {
            Map<String, Object> authTree = new HashMap<>();
            authTree.put("id", sysMenu.getId());
            authTree.put("name", sysMenu.getName());
            authTree.put("pId", sysMenu.getParentId());
            authTree.put("open", true);
            authTree.put("checked", false);
            if (roleMenusMap.get(sysMenu.getId()) != null) {
                authTree.put("checked", true);
            }
            authTrees.add(authTree);
        }
        return authTrees;
    }

    @GetMapping("/{roleCodes}")
    public List<SysMenu> getRoleMenuList(@PathVariable String roleCodes) throws Exception {
        List<SysMenu> result = null;
        if (StringUtils.isNotEmpty(roleCodes)) {
            List<String> roleSet = (List<String>) Convert.toCollection(ArrayList.class, String.class, roleCodes);
            result = sysMenuService.findByRoleCodes(roleSet, SystemConstants.PERMISSION);
        }
        return result;
    }

    @PostMapping("/granted")
    public Result setMenuToRole(@RequestBody SysMenu sysMenu) throws Exception {
        sysMenuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds());
        return Result.succeed("操作成功");
    }

    @GetMapping("/findAlls")
    public PageResult<SysMenu> findAlls(@CurrentUser SysUser user) throws Exception {
        List<SysMenu> list = sysMenuService.findAll();
        return PageResult.<SysMenu>builder().data(list).code(0).count(list.size()).build();
    }

    @GetMapping("/findOnes")
    public PageResult<SysMenu> findOnes() throws Exception {
        List<SysMenu> list = sysMenuService.findOnes();
        return PageResult.<SysMenu>builder().data(list).code(0).count(list.size()).build();
    }

    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody SysMenu menu) throws Exception {
        try {
            sysMenuService.saveOrUpdate(menu);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            log.error("save or update menu error", e);
            return Result.failed("操作失败");
        }
    }

    /**
     * 当前登录用户的菜单
     */
    @GetMapping("/current")
    public List<SysMenu> findMenu(@CurrentUser SysUser user) throws Exception {
        List<SysRole> roles = user.getRoles();
        if (CollectionUtil.isEmpty(roles)) {
            return Collections.emptyList();
        }
        List<SysMenu> menus = sysMenuService.findByRoleCodes(roles.parallelStream().map(SysRole::getCode).collect(Collectors.toList()), SystemConstants.MENU);
        return treeBuilder(menus);
    }
}
